<template>
<view>
  <view>
    <u-form :model="param" ref="uQueryForm">
      <u-row>
        <u-col span="2">
          <u--text type="primary" text="扫码"></u--text>
        </u-col>
        <u-col span="8">
          <u--input
              placeholder="请扫码"
              border="surround"
              :readonly="initFlag"
              v-model="param.searchKey"
          ></u--input>
        </u-col>
      </u-row>

      <u-row v-show="false">
        <u-col span="3">
          <u--text type="primary" text="物料编码"></u--text>
        </u-col>
        <u-col span="8">
          <u--input
              placeholder="请输入物料编码"
              border="surround"
              v-model="param.invCode"
              clearable
          ></u--input>
        </u-col>
      </u-row>

      <u-row v-show="false">
        <u-col span="3">
          <u--text type="primary" text="采购订单"></u--text>
        </u-col>
        <u-col span="8">
          <u--input
              placeholder="请输入采购订单"
              border="surround"
              v-model="param.orderNo"
              clearable
          ></u--input>
        </u-col>
      </u-row>

      <u-row v-show="false">
        <u-col span="2">
          <u--text type="primary" text="供应商"></u--text>
        </u-col>
        <u-col span="8">
          <u--input
              placeholder="请输入供应商"
              border="surround"
              v-model="param.suppLierName"
              clearable
          ></u--input>
        </u-col>
      </u-row>
    </u-form>
    <u-divider text="分割线" :dot="true"></u-divider>
  </view>

  <u-list @scrolltolower="scrollTolower"  @scrollWithAnimation="true" :key="listKey">
    <u-list-item v-for="(item, index) in items" :key="index" class="custom-list-item" >
      <view @click="handleSubmit(item)">
        <u-cell :title="`供应商：${item.suppLierName}`"></u-cell>
        <u-cell :title="`订单号：${item.orderNo}`"></u-cell>
        <u-cell :title="`物料编码：${item.invCode}`"></u-cell>
        <u-cell :title="`物料名称：${item.invName}`"></u-cell>
        <u-cell :title="`物料型号：${item.invSpec ? item.invSpec: ''}`"></u-cell>
        <u-row>
          <u-col span="6">
            <u-cell :title="`仓库：${item.whName}`"></u-cell>
          </u-col>
          <u-col span="12">
            <u-cell :title="`收货计划数量：${item.qty}`"></u-cell>
          </u-col>
        </u-row>
        <u-row>
          <u-col span="6">
            <u-cell :title="`单位：${item.unitName}`"></u-cell>
          </u-col>
          <u-col span="12">
            <u-cell :title="`累计收货数量：${item.actQtySum}`"></u-cell>
          </u-col>
        </u-row>
        <u-cell :title="`任务号：${item.taskNo}`"></u-cell>
      </view>
    </u-list-item>
  </u-list>

  <u-loading-icon :show="loading" text="加载中" textSize="18"></u-loading-icon>

  <u-modal :show="show" :title="title" showCancelButton confirmText="提交" @cancel="cancelForm"
           :showConfirmButton="confirmDisabled" @confirm="submitForm">
    <u--form :model="form" ref="uForm">
      <u-form-item label="编码"  >
        <u--input
            placeholder="请输入物料编码"
            border="surround"
            readonly
            v-model="form.invCode"
        ></u--input>
      </u-form-item>
      <u-form-item label="批次" v-show="form.isbatchNo">
        <u--input
            placeholder="请输入批次号"
            border="surround"
            clearable
            v-model="form.batchNo"
        ></u--input>
      </u-form-item>
      <u-col span="10">
        <u-form-item label="生产日期" @click="DateShow = true" v-show="form.isEffective">
          <u--input
              placeholder="请输入生产日期"
              border="surround"
              clearable
              :disabled="true"
              v-model="form.productionDate"
          ></u--input>
        </u-form-item>
      </u-col>
      <u-form-item label="计划">
        <u--input
            border="surround"
            readonly
            v-model="form.qty"
        ></u--input>
      </u-form-item>
      <u-form-item label="累计">
        <u--input
            border="surround"
            readonly
            v-model="form.actQtySum"
        ></u--input>
      </u-form-item>
      <u-form-item label="提交数量">
        <u--input
            border="surround"
            clearable
            color="red"
            type="number"
            v-model="form.actQty"
        ></u--input>
      </u-form-item>
      <u-calendar :show="DateShow" :mode="DateMmode" @close="DateShow = false" @confirm="confirmDate"></u-calendar>
    </u--form>
  </u-modal>

  <view class="fixed-bottom">
    <u-button @click="scanCode">扫码收货</u-button>
  </view>
</view>
</template>
<script >
import UButton from "../../../../uview-ui/components/u-button/u-button.vue";
import UForm from "../../../../uview-ui/components/u--form/u--form.vue";
import UniDataSelect from "../../../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import UInput from "../../../../uview-ui/components/u--input/u--input.vue";
import URow from "../../../../uview-ui/components/u-row/u-row.vue";
import UCol from "../../../../uview-ui/components/u-col/u-col.vue";
import UFormItem from "../../../../uview-ui/components/u-form-item/u-form-item.vue";
import UList from "../../../../uview-ui/components/u-list/u-list.vue";
import UListItem from "../../../../uview-ui/components/u-list-item/u-list-item.vue";
import UCell from "../../../../uview-ui/components/u-cell/u-cell.vue";
import {getDetail, searchList, submit} from "@/api/work/wareHourse/asnTask";
import ULoadingIcon from "../../../../uview-ui/components/u-loading-icon/u-loading-icon.vue";
import UModal from "../../../../uview-ui/components/u-modal/u-modal.vue";
import UCalendar from "../../../../uview-ui/components/u-calendar/u-calendar.vue";
import UDivider from "../../../../uview-ui/components/u-divider/u-divider.vue";

export default {
  components: {
    UDivider,
    UCalendar, UModal,
    ULoadingIcon,
    UCell, UListItem, UList,
    UFormItem,
    UCol, URow, UInput, UniDataSelect,
    UForm,
    UButton
  },
  data() {
    return {
      items: [],
      listKey: Date.now(),
      param: {
        pageNum: 0,
        pageSize: 10,
        invCode: null,
        batchNo: null,
        suppLierName: null,
        orderNo: null,
        productionDate: null,
        searchKey: null,
      },
      DateShow: false,
      DateMmode: 'single',
      loading: false,
      show: false,
      title: null,
      form: {},
      confirmDisabled: true,
      handlePdaScan: null,
      initFlag: false,
    };
  },
  onLoad() {
    // 初始化扫码功能
    this.initScan();
  },
  beforeDestroy() {
    if (this.initFlag) {
      let globalEvent = uni.requireNativePlugin('globalEvent');
      globalEvent.removeEventListener('iDataBarcodeEvent', this.handlePdaScan);
    }
  },
  methods: {
    loadMore() {
      this.loading = true;
      this.param.pageNum = this.param.pageNum + 1;
      searchList(this.param).then(res => {
        this.listKey = Date.now();
        this.total = res.total;
        if (res.rows.length > 0) {
          res.rows.forEach(item => this.items.push(item));
        } else {
          uni.showToast({
            title: '没有收货任务！',
            icon: 'none',
            duration: 2000
          });
        }
        this.loading = false;
        if (this.total === 1 && this.param.pageNum === 1) {
          this.handleSubmit(res.rows[0]);
        }
      });
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.param.searchKey = res.result;
          this.checkSearchKey(res.result);
        },
        fail: (err) => {
          this.$modal.showToast('扫码失败: ' + (err.errMsg || err));
        }
      });
    },
    initScan() {
      try {
        let barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule");
        if (!barcodeModel) {
          console.log("不支持红外扫码功能");
          this.$modal.showToast('该设备不支持红外扫码');
          this.initFlag = false;
          return false;
        }
        
        barcodeModel.initScan((ret) => {
          if (ret.code === 'success') {
            console.log("红外扫码初始化成功");
          } else {
            console.log("红外扫码初始化失败", ret);
          }
        });
        
        barcodeModel.setOutputMode(4,(ret) => {
          if (ret.code === 'success') {
            console.log("扫码输出模式设置成功");
          } else {
            console.log("扫码输出模式设置失败", ret);
          }
        });
        
        let globalEvent = uni.requireNativePlugin('globalEvent');
        let that = this;
        this.handlePdaScan = function(res) {
          console.log("红外扫码结果:", res);
          that.checkSearchKey(res.barcode);
        };
        globalEvent.addEventListener('iDataBarcodeEvent', this.handlePdaScan);
        this.initFlag = true;
        return true;
      } catch (e) {
        console.error("红外扫码初始化异常:", e);
        this.$modal.showToast('红外扫码初始化失败: ' + (e.message || e));
        this.initFlag = false;
        return false;
      }
    },
    resetDataNew() {
      this.param = {
        pageNum: 0,
        pageSize: 10,
        invCode: null,
        batchNo: null,
        suppLierName: null,
        orderNo: null,
        productionDate: null,
        searchKey: null,
      }
    },
    checkSearchKey(result) {
      console.log("扫码内容:", result);
      this.resetDataNew();
      this.param.searchKey = result;
      this.confirmDisabled = false;
      this.tempItem = null;
      if (result === null || result === '' || result.length < 11 || !result.toUpperCase().includes("ALL")) {
        this.$modal.showToast( '请扫描正确的条码:' + result);
        return;
      }
      let datas = result.split("#");
      if (datas.length === 7 && result.toUpperCase().includes("ALL")) {
        this.param.invCode = datas[0];
        this.param.batchNo = datas[1];
        this.param.orderNo = datas[3];
        if (datas[4] != null && datas[4] !== undefined && datas[4] !== '') {
          let DateFormat = this.determineDateFormat(datas[4]);
          if ('YYYYMMDD' === DateFormat) {
            this.param.productionDate = this.convertDateFormat(datas[4]);
          } else if ('YYYY-MM-DD' === DateFormat) {
            this.param.productionDate = datas[4];
          } else {
            this.$modal.showToast(  '条码中生成日期格式未知，请联系管理员：' + datas[4]);
            return;
          }
        }
        this.searchList();
      } else {
        this.$modal.showToast('扫码失败, 请扫描正确的条码: ' + result);
      }
    },
    determineDateFormat(dateString) {
      const t1 = /^\d{4}-\d{2}-\d{2}$/;
      const t2 = /^\d{8}$/;
      if (t1.test(dateString)) {
        return 'YYYY-MM-DD';
      } else if (t2.test(dateString)) {
        return 'YYYYMMDD';
      } else {
        return '未知格式';
      }
    },
    convertDateFormat(dateString) {
      const regex = /^\d{8}$/;
      if (!regex.test(dateString)) {
        throw new Error('输入的日期格式不正确');
      }
      // 使用字符串切片方法来插入连字符
      return `${dateString.slice(0, 4)}-${dateString.slice(4, 6)}-${dateString.slice(6, 8)}`;
    },
    confirmDate(e) {
      this.form.productionDate = e[0];
      this.DateShow = false;
    },
    searchList() {
      this.items = [];
      setTimeout(()=> {this.loadMore();}, 100);
    },
    scrollTolower() {
      if (this.items.length >= this.total) {
        this.$modal.showToast("没有更多数据了");
        return;
      }
      // 计算最大页数
      let maxPage = Math.ceil(this.total / this.param.pageSize);
      if (maxPage === this.param.pageNum) {
        this.$modal.showToast("已到最后一页");
        return;
      }
      this.loadMore()
    },
    resetData(row) {
      this.form.invCode = row.invCode;
      this.form.invName = row.invName;
      this.form.batchNo = this.param.batchNo;
      this.form.productionDate = this.param.productionDate;
      this.form.actQty = this.form.qty - this.form.actQtySum;
    },
    handleSubmit(row) {
      getDetail(row).then(res => {
        if (res.code === 200) {
          this.form = res.data;
          this.form.invCode = row.invCode;
          this.resetData(row);
          if (this.form.isSerialNo) {
            this.$modal.showToast("不支持序列号物料收货！");
            return;
          }
          this.tempItem = row;
          this.show = true;
          this.confirmDisabled = true;
        } else {
          this.$modal.showToast('获取数据失败: ' + (res.msg || ''));
        }
      }).catch(err => {
        this.$modal.showToast('获取数据失败: ' + (err.message || err));
      });
    },
    cancelForm() {
      this.show = false;
    },
    submitForm() {
      this.confirmDisabled = false;
      if (this.form.actQty == null || this.form.actQty <= 0 ||
          this.form.actQty > (this.form.qty - this.form.actQtySum)) {
        this.$modal.showToast("提交数量不对！");
        this.confirmDisabled = true;
        return;
      }
      if (this.form.isbatchNo && (this.form.batchNo === null || this.form.batchNo === '')) {
        this.$modal.showToast("请输入批次号！");
        return;
      }
      if (this.form.isEffective === 1 && (this.form.productionDate === '' || this.form.productionDate === null)) {
        this.$modal.showToast("请输入生产日期！");
        this.confirmDisabled = true;
        return;
      }
      submit(this.form).then(res => {
        if (res.msg === '操作成功') {
          let index = this.items.indexOf(this.tempItem);
          if (index > -1) {
            this.items.splice(index, 1);
          }
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
          });
          this.confirmDisabled = true;
          this.show = false;
        } else {
          uni.showToast({
            title: '提交失败',
            icon: 'error',
            duration: 2000
          });
          this.confirmDisabled = true;
        }
      }).catch(err => {
        this.$modal.showToast('提交失败:'+ (err.message || err));
        this.confirmDisabled = true;
      })
    },
  },
};
</script>
<style>
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  /* 可能需要设置一些内边距或外边距以保持良好的视觉效果 */
  padding: 10px;
  text-align: center;
  background-color: #fff; /* 背景色与页面背景色相同或透明，视设计而定 */
  z-index: 999; /* 确保按钮在最上层 */
}
.custom-list-item {
  background-color: #ADD8E6;

  /* 如果需要让整个列表项点击区域都生效，可能还需要下面这行 */
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
  height: 100%; /* 根据实际情况调整高度 */
}

</style>